<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>BroadcastChannel Page 1</title>
    <style>
      * {
        font-size: 28px;
      }
    </style>
  </head>
  <body>
    <h3>Page 2</h3>

    <section style="margin-top: 50px; text-align: center">
      <input id="inputMessage" value="测试消息" />
      <input type="button" value="发送消息" id="btnSend" />
      <section id="messages">
        <p>收到的消息：</p>
      </section>
    </section>

    <script>
      let messagesEle = document.getElementById("messages");
      let messageEl = document.getElementById("inputMessage");
      let btnSend = document.getElementById("btnSend");

      let channel = new BroadcastChannel("channel-BroadcastChannel");
      channel.addEventListener("message", function (ev) {
        let msgEl = document.createElement("p");
        msgEl.innerText = ev.data.date + " " + ev.data.from + ":" + ev.data.message;
        messagesEle.appendChild(msgEl);
      });

      btnSend.addEventListener("click", function () {
        let message = messageEl.value;
        channel.postMessage({
          date: new Date().toLocaleString(),
          message,
          from: "page 2",
        });
      });
    </script>
  </body>
</html>
